import java.io.Serializable;
import java.util.Iterator;
import java.util.TreeMap;


public class Question implements Serializable {
	/**
	 * 
	 */
	private static final long serialVersionUID = 3900138613448390226L;
	
	private TreeMap<Integer, Answer> answers;
	private String question;
	private boolean finished;
	private String summary="";
	
	private static int 	HOUR = 1,
						DAY = 8,
						WEEK = 5*DAY,
						MONTH = 4*WEEK,
						YEAR  = 11*MONTH;
	
	public Question(String question) {
		answers = new TreeMap<Integer, Answer>();

		this.question = question;
		finished = false;
	}
	
	public void answer(Answer ans, int id) {
		answers.put(id, ans);
	}
	
	public String getQuestion() {
		return question;
	}
	
	private String printAnswers(double conv, String outputUnit) {
		StringBuilder sb = new StringBuilder();
		
		sb.append(question + "\n\n");
		
		Iterator<Answer> itr = answers.values().iterator();
		
		while(itr.hasNext()) {
			Answer ans = itr.next();
			sb.append("Estimation: " + ans.getEstimation()*conv + " " + outputUnit + "\n");
			sb.append("Motivation:\n");
			sb.append(ans.getMotivation() + "\n\n");
		}
		
		return sb.toString();
	}
	
	private String printMean(double conv, String outputUnit) {
		Iterator<Answer> itr = answers.values().iterator();
		double sum = 0;
		double max = Integer.MIN_VALUE;
		double min = Integer.MAX_VALUE;
		
		while(itr.hasNext()) {
			Answer a = itr.next();
			double est = a.getEstimation() * conv;
			sum += est;
			
			if(est > max) {
				max = est;
			} 
			
			if (est < min) {
				min = est;
			}
		}
	
		
		StringBuilder sb = new StringBuilder();
		sb.append("Mean: " + sum/answers.size() + " " + outputUnit + "\n");
		sb.append("Max: " + max + " " + outputUnit + "\n");
		sb.append("Min: " + min + " " + outputUnit + "\n");
		
		return sb.toString();
	}
	
	public Answer getAnswer(int id) {
		return answers.get(id);
	}
	
	public void setFinished(boolean f){
		finished = f;
	}
	
	public boolean isFinished(){
		return finished;
	}
	
	public String toString(){
		return question;
	}
	
	public String getSummary(){
		return summary + "";
	}
	
	public void finalEstimate(int finalEst) {
		answers = new TreeMap<Integer, Answer>();
		answers.put(0, new Answer(finalEst, "Finalized after discussion."));
	}
	
	public void genSummary(double conv, String convUnit, String outputUnit){
		
		switch(convUnit) {
		case "hours":
			conv *= HOUR;
			break;
		case "days":
			conv *= DAY;
			break;
		case "weeks":
			conv *= WEEK;
			break;
		case "months":
			conv *= MONTH;
			break;
		case "years":
			conv *= YEAR;
			break;
		case "none":
			conv = 1;
		}
		
		
		switch(outputUnit) {
		case "hours":
			conv /= HOUR;
			break;
		case "days":
			conv /= DAY;
			break;
		case "weeks":
			conv /= WEEK;
			break;
		case "months":
			conv /= MONTH;
			break;
		case "years":
			conv /= YEAR;
			break;
		}
		
		summary = printAnswers(conv, outputUnit) + printMean(conv, outputUnit) + "";
	}
}
